// 存储最新的分析结果
let lastAnalysisResult = null;

document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('dropZone');
    const imageInput = document.getElementById('imageInput');
    const imagePreview = document.getElementById('imagePreview');
    const previewImg = document.getElementById('previewImg');

    // 点击上传区域触发文件选择
    dropZone.addEventListener('click', () => imageInput.click());

    // 处理文件选择
    imageInput.addEventListener('change', handleFileSelect);

    // 处理拖放
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('dragover');
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            imageInput.files = files;
            handleFileSelect({ target: imageInput });
        }
    });
});

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    // 验证文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!validTypes.includes(file.type)) {
        alert('请选择有效的图片文件（JPG, PNG, GIF）');
        return;
    }

    // 预览图片
    const reader = new FileReader();
    reader.onload = function(e) {
        const imagePreview = document.getElementById('imagePreview');
        const previewImg = document.getElementById('previewImg');
        previewImg.src = e.target.result;
        imagePreview.style.display = 'block';
    };
    reader.readAsDataURL(file);
}

// 获取服务类型
function getServiceType(selectedType) {
    const typeMap = {
        '通用基线检测': 'baselineCheck',
        '内容治理检测': 'tonalityImprove',
        '恶意图片检测': 'riskDetection',
        '头像图片检测': 'profilePhotoCheck',
        '帖子评论图片检测': 'postImageCheck',
        '营销素材检测': 'advertisingCheck',
        '直播截图检测': 'liveStreamCheck',
        'AIGC图片检测': 'aigcCheck'
    };
    return typeMap[selectedType] || 'baselineCheck';
}

// 分析图片
async function analyzeImage() {
    const imageInput = document.getElementById('imageInput');
    const imageType = document.getElementById('imageType');
    const resultArea = document.getElementById('analysisResult');
    const downloadBtn = document.getElementById('downloadBtn');
    
    if (!imageInput.files || imageInput.files.length === 0) {
        alert('请先选择图片文件！');
        return;
    }

    // 显示加载状态
    resultArea.innerHTML = '正在分析中...';
    downloadBtn.style.display = 'none';
    
    try {
        const formData = new FormData();
        formData.append('image', imageInput.files[0]);
        formData.append('serviceType', getServiceType(imageType.value));

        const response = await fetch('http://localhost:5000/api/analyze-image', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            throw new Error('网络请求失败');
        }

        const data = await response.json();
        
        if (data.error) {
            throw new Error(data.error);
        }

        displayResult(data);
        
    } catch (error) {
        resultArea.innerHTML = `<div style="color: red; padding: 10px;">分析过程中出现错误：${error.message}</div>`;
        console.error('Error:', error);
        downloadBtn.style.display = 'none';
    }
}

// 显示结果
function displayResult(data) {
    const resultArea = document.getElementById('analysisResult');
    const downloadBtn = document.getElementById('downloadBtn');

    if (data.code === 200 && data.data) {
        const result = data.data;
        const detectionResults = result.Result || [];
        const riskLevel = (result.RiskLevel || 'none').toLowerCase();

        // 风险等级配置
        const riskDetails = {
            high: {
                text: '高风险',
                color: '#ff4d4f',
                icon: '⚠️',
                description: '检测到严重风险内容，建议立即处理'
            },
            medium: {
                text: '中风险',
                color: '#fa8c16',
                icon: '⚠️',
                description: '检测到潜在风险内容，建议人工复核'
            },
            low: {
                text: '低风险',
                color: '#fadb14',
                icon: 'ℹ️',
                description: '检测到轻微风险内容，建议关注'
            },
            none: {
                text: '无风险',
                color: '#52c41a',
                icon: '✅',
                description: '未检测到风险内容'
            }
        };

        // 构建风险等级显示块
        const currentRisk = riskLevel;
        const riskBlock = `
            <div style="
                background: ${riskDetails[currentRisk].color}10;
                border-left: 4px solid ${riskDetails[currentRisk].color};
                padding: 16px;
                margin: 16px 0;
                border-radius: 4px;
            ">
                <div style="display: flex; align-items: center; gap: 12px;">
                    <span style="font-size: 1.5em; color: ${riskDetails[currentRisk].color}">
                        ${riskDetails[currentRisk].icon}
                    </span>
                    <div>
                        <h3 style="margin: 0; color: ${riskDetails[currentRisk].color}">
                            ${riskDetails[currentRisk].text}
                        </h3>
                        <p style="margin: 8px 0 0; color: #666">
                            ${riskDetails[currentRisk].description}
                        </p>
                    </div>
                </div>
            </div>
        `;

        // 存储完整分析结果用于下载
        lastAnalysisResult = {
            检测时间: new Date().toLocaleString(),
            检测类型: document.getElementById('imageType').value,
            风险等级: riskLevel,
            原始数据: JSON.parse(JSON.stringify(data.data)) // 包含完整Result数据
        };

        // 构建显示内容
        let resultHTML = `
            <div style="padding: 20px;">
                ${riskBlock}

                <div style="margin: 20px 0;">
                    <h3 style="color: #1890ff; border-bottom: 1px solid #eee; padding-bottom: 8px;">
                        <span style="margin-right: 10px">🔍</span>
                        详细检测结果（共 ${detectionResults.length} 项）
                    </h3>
                    <div style="margin-top: 15px;">
                        ${detectionResults.map((item, index) => `
                            <div style="
                                padding: 15px;
                                margin-bottom: 12px;
                                background: ${index % 2 === 0 ? '#f8f9fa' : 'white'};
                                border-radius: 6px;
                                border-left: 4px solid ${getRiskColorByConfidence(item.Confidence)};
                            ">
                                <div style="display: flex; justify-content: space-between;">
                                    <div style="flex: 1;">
                                        <div style="font-weight: 500; color: #333;">
                                            ${index + 1}. ${item.Description}
                                            ${item.Label.includes('_lib') ? 
                                                '<span style="color: #eb2f96; font-size: 0.9em;">(自定义库命中)</span>' : ''}
                                        </div>
                                        <div style="color: #666; margin-top: 8px; font-size: 0.9em;">
                                            <div>🔖 分类标签：${item.Label}</div>
                                            ${item.Confidence ? `
                                                <div style="margin-top: 6px;">
                                                    <span style="display: inline-block; width: 80px;">置信度：</span>
                                                    <span style="color: ${getRiskColorByConfidence(item.Confidence)}">
                                                        ${item.Confidence}%
                                                    </span>
                                                </div>
                                            ` : ''}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;

        resultArea.innerHTML = resultHTML;
        downloadBtn.style.display = 'block';
    } else {
        resultArea.innerHTML = `
            <div style="text-align: center; padding: 20px; color: #52c41a;">
                <h3>√ 未检测到风险</h3>
                <p style="color: #666; margin-top: 10px;">该图片通过所有安全检测</p>
            </div>`;
        downloadBtn.style.display = 'none';
    }
}

// 添加辅助函数
function getRiskColor(riskLevel) {
    return {
        high: '#ff4d4f',
        medium: '#faad14',
        low: '#52c41a',
        none: '#52c41a'
    }[riskLevel?.toLowerCase()] || '#666';
}

function getRiskLevelText(riskLevel) {
    return {
        high: '高风险',
        medium: '中风险',
        low: '低风险',
        none: '无风险'
    }[riskLevel?.toLowerCase()] || '未知风险';
}

// 新增辅助函数：根据置信度获取颜色
function getRiskColorByConfidence(confidence) {
    if (!confidence) return '#666';
    if (confidence >= 80) return '#ff4d4f';
    if (confidence >= 60) return '#fa8c16';
    return '#fadb14';
}

function getRiskLevelByConfidence(confidence) {
    if (!confidence) return '未知';
    if (confidence >= 80) return '高风险';
    if (confidence >= 60) return '中风险';
    return '低风险';
}

// 下载结果功能
function downloadResult() {
    if (!lastAnalysisResult) {
        alert('没有可下载的分析结果');
        return;
    }

    const blob = new Blob(
        [JSON.stringify(lastAnalysisResult, null, 2)], 
        { type: 'application/json;charset=utf-8' }
    );
    
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `图片分析结果_${new Date().toISOString().slice(0,19).replace(/[:-]/g, '')}.json`;
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(link.href);
} 